package com.android.interfata;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URI;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


public class XMLfunctions
{

	public final static Document XMLfromString(String xml)
	{
		
		Document doc = null;
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try
        {
        	
			DocumentBuilder db = dbf.newDocumentBuilder();
			
			InputSource is = new InputSource();
	        is.setCharacterStream(new StringReader(xml));
	        doc = db.parse(is); 
	        
		} 
        catch (ParserConfigurationException e)
        {
			System.out.println("XML parse error: " + e.getMessage());
			return null;
		} 
        catch (SAXException e) 
        {
			System.out.println("Wrong XML file structure: " + e.getMessage());
            return null;
		} 
        catch (IOException e)
        {
			System.out.println("I/O exeption: " + e.getMessage());
			return null;
		}
		       
        return doc;
        
	}
	
	/** Returns element value
	  * @param elem element (it is XML tag)
	  * @return Element value otherwise empty String
	  */
	
	 public final static String getElementValue( Node elem )
	 {
	     Node kid;
	     if( elem != null)
	     {
	         if (elem.hasChildNodes())
	         {
	             for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() )
	             {
	                 if( kid.getNodeType() == Node.TEXT_NODE  )
	                 {
	                     return kid.getNodeValue();
	                 }
	             }
	         }
	     }
	     return "";
	 }
	 
	 public static String getXML(String requestStr) throws Exception
	    {
	        BufferedReader in = null;
	        String page = null;
	        try
	        {
	                     
	            HttpClient client = new DefaultHttpClient();
	            HttpGet request = new HttpGet();
	            request.setURI(new URI("http://mail.pioneerinvestments.ro:333//WebServicies/Users.asmx/" + requestStr));
	            HttpResponse response = client.execute(request);
	        		       
	            in = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
	            StringBuffer sb = new StringBuffer("");
	            String line = "";
	            String NL = System.getProperty("line.separator");
	            
	            while ((line = in.readLine()) != null)
	            {
	                sb.append(line + NL);
	            }
	            
	            in.close();
	            page = sb.toString();
	         //   System.out.println(page);
	        } 
     	finally
     	{
	            if (in != null)
	            {
	                try
	                {
	                    in.close();
	                } 
	                catch (IOException e)
	                {
	                    e.printStackTrace();
	                }
	            }
     	}
     	return page;
	 }
	 
	 public static String getStatistics(String requestStr) throws Exception
	 {
	        BufferedReader in = null;
	        String page = null, result = null, link = null;
	        int poz;
	        try
	        {
	                     
	            HttpClient client = new DefaultHttpClient();
	            HttpGet request = new HttpGet();
	            request.setURI(new URI(requestStr));
	            HttpResponse response = client.execute(request);
	        		       
	            in = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
	            StringBuffer sb = new StringBuffer("");
	            String line = "";
	            String NL = System.getProperty("line.separator");
	            
	            if ((line = in.readLine()) != null)
	            {
	                sb.append(line + NL);
	            }
	          //  http://mail.pioneerinvestments.ro:333/WebCharts%5C12918016-9b49-494e-8fdc-cc2ecb0a1b6b.Png
	            in.close();
	            page = sb.toString();
	            poz = page.indexOf("WebCharts");
	            
	            if(poz != -1) 
	            {
	            	result = page.substring(poz, page.length());
	            	link = "http://mail.pioneerinvestments.ro:333/" + result;
	            	
	            }
	            
	            System.out.println("link" + link);
	        } 
		  	finally
		  	{
			            if (in != null)
			            {
			                try
			                {
			                    in.close();
			                } 
			                catch (IOException e)
			                {
			                    e.printStackTrace();
			                }
			            }
		  	}
		  	return link;
	 }
	 
	 
	public static int numResults(Document doc, String tagName)
	{		
		NodeList nl = doc.getElementsByTagName(tagName);
				
		int res = -1;

		try
		{
			res = nl.getLength();
			
		}
		catch(Exception e )
		{
			res = -1;
		}
		
		return res;
	}

		
	public static String getValue(Element item, String str)
	{		
		NodeList n = item.getElementsByTagName(str);		
		return XMLfunctions.getElementValue(n.item(0));
	}
}
